import cgi
import re

from jinja2 import Environment, PackageLoader, Template, FileSystemLoader, evalcontextfilter, Markup, escape

import mdf.debug as debug
import mdf.config as config
#import mdf.writeup as writeup
#import mdf.utils as utils
import mdf.bbcode as bbcode

def cnv_to_name( art_name ):
	art_name = art_name.replace(" ","_")
	art_name = art_name.replace("+","_")
	art_name = art_name.lower()
	return art_name

html_escape_table = {
	"&": "&amp;",
	'"': "&quot;",
	"'": "&apos;",
	">": "&gt;",
	"<": "&lt;",
}

def to_html_entity( s ):
	"""Produce entities within text."""
	return "".join(html_escape_table.get(c,c) for c in s)

_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
@evalcontextfilter
def nl2br(eval_ctx, value):
	flag_stop = False
	result = ""
	for el in value.split( "\n" ):
		
		if el.find( bbcode.CODE_NL2BR ) != -1:
			el = el.replace(bbcode.CODE_NL2BR,"")
			if flag_stop == True:
				flag_stop = False
			else:
				flag_stop = True
		
		if flag_stop == False:
			result = result + el + "<br/>\n"
		else:
			result = result + el + "\n"
	
	return result
